<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>订单管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-spin :spinning="spinning">
      <div class="pageTabsWhole" style="margin-top:24px;">
        <a-tabs
          class="table_tab"
          defaultActiveKey
          :animated="false"
          :tabBarStyle="{margin:0}"
          :tabBarGutter="16"
          v-model="activeKey"
          @change="onChangeStatus"
        >
          <a-tab-pane v-for="v in orderTypes" :key="v.key" :tab="v.title"></a-tab-pane>
        </a-tabs>
      </div>
      <div class="pageContentWhole">
        <a-row>
          <a-col :span="24">
            <a-form layout="inline">
              <a-form-item label="客户名称">
                <a-input v-model="searchForm.custName" />
              </a-form-item>
              <a-form-item label="海船公司">
                <a-input v-model="searchForm.seagoingShipCompanyName" />
              </a-form-item>
              <a-form-item>
                <a-input-group compact>
                  <a-select
                    v-model="searchForm.typeIndex"
                    @change="onChangeTypeOptions"
                    class="selectWidth"
                  >
                    <a-select-option v-for="v in typeOptions" :key="v.key">{{v.title}}</a-select-option>
                  </a-select>
                  <a-input style="width: 200px" @change="onNameChange" />
                </a-input-group>
              </a-form-item>
              <a-form-item label="订单类型">
                <a-select v-model="searchForm.orderType" class="selectInputWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in OrderOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="结算类型">
                <a-select v-model="searchForm.settlementType" class="selectInputWidth">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="所属销售">
                <a-select v-model="searchForm.sellerId" class="selectWidth">
                  <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="起运港">
                <a-input v-model="searchForm.startPortName" />
              </a-form-item>
              <a-form-item label="目的港">
                <a-input v-model="searchForm.endPortName" />
              </a-form-item>
              <a-form-item>
                <a-input-group compact>
                  <a-select
                    v-model="searchForm.dateIndex"
                    @change="onDateTypeChange"
                    class="selectWidth"
                  >
                    <a-select-option v-for="(v, k) in dateOptions" :key="k">{{v}}</a-select-option>
                  </a-select>
                  <a-range-picker @change="onDateChange">
                    <a-icon slot="suffixIcon" type="calendar" />
                  </a-range-picker>
                </a-input-group>
              </a-form-item>

              <a-form-item>
                <a-button type="primary" @click="handleSubmit1">查询</a-button>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </div>

      <!-- 订单列表 -->
      <a-row class="orderItem ordertem_de">
        <a-col :span="24">
          <!-- <a-spin :spinning="spinning"> -->
          <template v-if="tableData.length > 0">
            <div v-for="(item, index) in tableData" :key="index" class="orderList">
              <a-card size="small">
                <template slot="title">
                  <a-descriptions :column="4" class="titleCard" style="padding-left:24px;">
                    <a-descriptions-item label="公司编号">{{item.orderCode||'--'}}</a-descriptions-item>
                    <a-descriptions-item label="运单号">{{item.seagoingShipOrderCode||'--'}}</a-descriptions-item>
                    <a-descriptions-item
                      label="驳船船名航次"
                    >{{item.shipName||'--'}}/{{item.shipVoyage||'--'}}</a-descriptions-item>
                    <a-descriptions-item
                      label="结算类型"
                    >{{checkSettlementTypeName(item.settlementType)}}</a-descriptions-item>
                  </a-descriptions>
                </template>
                <template slot="extra" style="padding-right:24px;">
                  <div class="orderTags">
                    <a-tag v-if="item.isUrgent===1" color="red" class="jia">加急</a-tag>
                  </div>
                </template>
                <div class="order_detail">
                  <a-descriptions :column="4" size="small">
                    <a-descriptions-item label="客户名称">{{item.custName}}</a-descriptions-item>
                    <a-descriptions-item label="货品名称">{{item.goodsName}}</a-descriptions-item>
                    <a-descriptions-item
                      :label="addressInfo(item.addressList, 1).opeType"
                      :span="2"
                    >{{addressInfo(item.addressList, 1).addressAll}}</a-descriptions-item>

                    <a-descriptions-item label="海船公司">{{item.seagoingShipCompanyName||'--'}}</a-descriptions-item>
                    <a-descriptions-item label="箱型箱量">{{item.containerType}}*{{item.containerNum}}</a-descriptions-item>
                    <a-descriptions-item
                      :span="2"
                      :label="addressInfo(item.addressList, 1).opeType ? '联系人' : ''"
                    >
                      <p
                        style="margin:0"
                      >{{addressInfo(item.addressList, 1).linkMan}} {{addressInfo(item.addressList, 1).linkManPhone}}</p>
                    </a-descriptions-item>

                    <a-descriptions-item label="订单类型">{{orderTypeStr(item.orderType)}}</a-descriptions-item>
                    <a-descriptions-item
                      label="起运/目的港"
                    >{{item.startPortName||'--'}} / {{item.endPortName||'--'}}</a-descriptions-item>
                    <a-descriptions-item
                      :label="addressInfo(item.addressList, 2).opeType"
                      :span="2"
                    >{{addressInfo(item.addressList, 2).addressAll}}</a-descriptions-item>

                    <a-descriptions-item label="所属销售">{{item.sellerName}}</a-descriptions-item>
                    <a-descriptions-item label="要求送达">{{item.requiredArriveTime}}</a-descriptions-item>
                    <a-descriptions-item
                      :label="addressInfo(item.addressList, 2).opeType ? '联系人' : ''"
                    >
                      <p
                        style="margin:0"
                      >{{addressInfo(item.addressList, 2).linkMan}} {{addressInfo(item.addressList, 2).linkManPhone}}</p>
                    </a-descriptions-item>
                    <a-descriptions-item v-if="item.addressList.length > 2">
                      <a @click="doOrderAudit(item.orderJiateId)">更多门点...</a>
                    </a-descriptions-item>
                  </a-descriptions>
                </div>
              </a-card>
              <a-card style="border-top:none" class="order_czuo">
                <template slot="title">
                  <a-descriptions :column="12" class="titleCard">
                    <a-descriptions-item :span="2">
                      <img src="../../../../static/images/order_zt1.png" />
                      {{statusStrs[item.status]}}
                    </a-descriptions-item>
                    <a-descriptions-item :span="2">
                      <img src="../../../../static/images/order_start.png" /> 销售下单
                      <span class="xdan_time">（{{item.createTime}}）</span>
                    </a-descriptions-item>
                  </a-descriptions>
                </template>
                <a-button
                  v-if="item.status===2 || item.status===3"
                  slot="extra"
                  type="primary"
                  ghost
                  @click="showBoxDetail(item.orderJiateId)"
                  style="margin-left: 12px;"
                >明细</a-button>
                <a-button
                  v-if="item.status===4"
                  slot="extra"
                  type="primary"
                  ghost
                  @click="orderReEdit(item.orderJiateId)"
                  style="margin-left: 12px;"
                >重新编辑</a-button>
                <a-button
                  v-if="item.status===4"
                  slot="extra"
                  type="primary"
                  ghost
                  @click="deleteOrder(item.orderJiateId)"
                  style="margin-left: 12px;"
                >删除</a-button>
                <a-button
                  slot="extra"
                  type="primary"
                  ghost
                  style="margin-left: 12px;"
                  @click="gotoDetail(item.orderJiateId)"
                >详情</a-button>
              </a-card>
            </div>
          </template>
          <div
            v-if="tableData.length === 0"
            style="margin: 0 24px 24px; padding: 20px 0; background: white;"
          >
            <a-empty />
          </div>
          <!-- </a-spin> -->
          <p class="orderPagination">
            <a-pagination
              show-size-changer
              show-quick-jumper
              :current="pagination.current"
              :total="pagination.total"
              :showTotal="pagination.showTotal"
              :pageSize="pagination.pageSize"
              @showSizeChange="pagination.onShowSizeChange"
              @change="pagination.onChange"
            />
          </p>
        </a-col>
      </a-row>
    </a-spin>

    <a-modal
      :visible="boxVisible"
      title="集装箱明细"
      centered
      destroyOnClose
      :maskClosable="false"
      :footer="null"
      width="720"
      @cancel="handleCancel"
    >
      <a-table
        :dataSource="boxData"
        :columns="boxColumns"
        :pagination="false"
        rowKey="orderTruckId"
      >
        <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import { mixin } from '@/common/settlement2'
import { OrderOptions } from '../options'
import { querySellerDown } from '@/api'
import { queryJiateOrderSellList, deleteOrderInfoJiate, queryJiateRelTruckOrderList } from '@/api/landCenter'

// 1待审核，2进行中，3已完成，4审核不通过
const orderTypes = [
  { key: '', title: '全部' },
  { key: '2', title: '进行中' },
  { key: '1', title: '待审核' },
  { key: '3', title: '已完成' },
  { key: '4', title: '审核不通过' }
]
const typeOptions = [
  { key: 'orderCode', title: '公司编号' },
  { key: 'seagoingShipOrderCode', title: '运单号' },
  { key: 'containerNo', title: '箱号' },
  { key: 'containerSealNo', title: '封号' }
]

const dateOptions = ['下单日期', '要求送达日期', '完成时间'] // 下单日期、要求送达日期
const statusStrs = ['', '待审核', '进行中', '已完成', '审核不通过']

const defaultSearchForm = (status) => (
  {
    status,
    custName: '',
    seagoingShipCompanyName: '',
    orderCode: '',
    orderType: '',
    settlementType: '',
    time1: null,
    time2: null,
    sellerId: null, // 所属销售
    startPortName: '', // 起运港
    endPortName: '', // 目的港
    containerNo: '', // 箱号
    containerSealNo: '', // 封号
    createTime1: null, // 下单日期
    createTime2: null, // 下单日期
    arriveTime1: null, // 要求送达时间
    arriveTime2: null, // 要求送达时间
    // 下拉词条，输入框暂存
    dateIndex: 0,
    typeIndex: 'orderCode'
  }
)

const statusArr = ['', '待接单', '待派单', '司机待接单', '司机待出发', '运输中', '已完成', '已结算', '已作废']

export default {
  mixins: [mixin],
  data () {
    const boxColumns = [
      {
        title: '序号',
        width: 60,
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '公司编号',
        dataIndex: 'truckOrderCode',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '运单号',
        dataIndex: 'seagoingShipOrderCode',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '箱号',
        dataIndex: 'containerNo',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '封号',
        dataIndex: 'containerSealNo',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '箱型',
        dataIndex: 'containerType',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '货名',
        dataIndex: 'goodsName',
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        customRender: (text, row, index) => {
          return text ? statusArr[text] : '--'
        }
      }
    ]

    return {
      activeKey: '',
      spinning: false,
      OrderOptions,
      orderTypes,
      typeOptions,
      dateOptions,
      statusStrs,
      sellers: [],
      searchForm: defaultSearchForm(),
      // 订单card start
      listData: [{ order: 1 }, { order: 2 }],
      columns: [],
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      pagination: {},
      // 订单card end
      boxColumns,
      boxData: [],
      boxVisible: false
    }
  },
  methods: {
    orderTypeStr (key) {
      const t = this.OrderOptions.filter(v => v.key === key)[0]
      if (t) return t.title
      return '--'
    },
    onChangeStatus (key) {
      this.activeKey = key
      this.searchForm = defaultSearchForm(key)
      querySellerDown({
        type: 1,
        dataRole: 'LAND_SELL'
      }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '全部'
            v.uiId = ''
          }
          return v
        })
        this.searchForm.sellerId = this.sellers[0].uiId
        this.handleSubmit()
      })
    },
    initSearchCondition1 () {
      Object.assign(this.searchForm, {
        orderCode: '', // 公司编号
        seagoingShipOrderCode: '', // 运单号
        containerNo: '', // 箱号
        containerSealNo: '' // 封号
      })
    },
    onChangeTypeOptions (value) {
      this.initSearchCondition1()
      this.searchForm[value] = this.searchForm.typexName
    },
    onNameChange (e) {
      this.searchForm.typexName = e.target.value
      this.onChangeTypeOptions(this.searchForm.typeIndex)
    },
    initSearchCondition2 () {
      Object.assign(this.searchForm, {
        createTime1: null,
        createTime2: null,
        arriveTime1: null,
        arriveTime2: null,
        completeTime1: null,
        completeTime2: null
      })
    },
    onDateTypeChange (value) {
      this.initSearchCondition2()
      if (value === 0) {
        this.searchForm.createTime1 = this.searchForm.time1
        this.searchForm.createTime2 = this.searchForm.time2
      } else if (value === 1) {
        this.searchForm.arriveTime1 = this.searchForm.time1
        this.searchForm.arriveTime2 = this.searchForm.time2
      } else if (value === 2) {
        this.searchForm.completeTime1 = this.searchForm.time1
        this.searchForm.completeTime2 = this.searchForm.time2
      }
    },
    onDateChange (date, dataStr) {
      this.searchForm.time1 = dataStr[0]
      this.searchForm.time2 = dataStr[1]
      this.onDateTypeChange(this.searchForm.dateIndex)
    },
    addressInfo (addressList, index) {
      let info = {}
      if (addressList.length > 0) {
        if (index === 1) {
          info = addressList[0]
        } else if (index === 2 && addressList.length > 1) {
          info = addressList[1]
        }
      }
      if (info.opeType === 1) {
        info.opeType = '装货'
      } else if (info.opeType === 2) {
        info.opeType = '卸货'
      } else if (info.opeType === 3) {
        info.opeType = '提箱'
      }

      if (info.addressType === 1) {
        info.addressAll = info.portName
      } else if (info.addressType === 2) {
        info.addressAll = `${info.province}${info.city}${info.area}${info.address}`
      }
      return info
    },
    getPagination (data) {
      const pages = data ? data.pages : 0
      return {
        current: this.pageNum,
        pageSize: this.pageSize,
        total: data ? data.total : 0,
        showTotal: total => `共${total}条记录 第${this.pageNum}/${pages}页`,
        onChange: pageNum => {
          this.pageNum = pageNum
          this.handleSubmit()
        },
        onShowSizeChange: (current, size) => {
          this.pageNum = current
          this.pageSize = size
          this.handleSubmit()
        }
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.spinning = true
      queryJiateOrderSellList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.spinning = false
        this.tableData = rsp.data.list
        this.pagination = this.getPagination(rsp.data)
      }).catch(() => { this.spinning = false })
    },
    gotoDetail (id) {
      this.$router.push('orderManage/' + id)
    },
    showBoxDetail (id) {
      queryJiateRelTruckOrderList({ orderJiateId: id }).then(rsp => {
        this.boxData = rsp.data
      })
      this.boxVisible = true
    },
    handleCancel () {
      this.boxVisible = false
      this.boxData = []
    },
    orderReEdit (id) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.$router.push('orderManageEdit/' + id)
    },
    deleteOrder (id) {
      if (!this.$root._bc.drop) {
        this.$message.error('您无此权限！')
        return
      }
      let _t = this
      _t.$confirm({
        title: '删除订单后将无法找回，确认删除？',
        okText: '删除',
        onOk () {
          deleteOrderInfoJiate({ orderJiateId: id }).then(rsp => {
            _t.$message.success('删除成功')
            _t.handleSubmit()
          })
        }
      })
    },
    doOrderAudit (id) {
      this.$router.push(`orderManage/${id}`)
    }
  },
  created () {
    this.pagination = this.getPagination()
  },
  mounted () {
    this.$nextTick(() => {
      let defaultActiveKey = this.$route.query.defaultActiveKey || ''
      if (defaultActiveKey) {
        this.onChangeStatus(defaultActiveKey)
      } else {
        querySellerDown({
          type: 1,
          dataRole: 'LAND_SELL'
        }).then(rsp => {
          this.sellers = rsp.data.map((v, i) => {
            if (!v.uiId) {
              v.name = '全部'
              v.uiId = ''
            }
            return v
          })
          this.searchForm.sellerId = this.sellers[0].uiId
          this.handleSubmit()
        })
      }
    })
  }
}
</script>

<style lang="less" scoped>
// overflow:hidden; white-space: nowrap; text-overflow: ellipsis;
</style>
